package cn.com.inossem.adapter;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.inossem.activity.FriendList;
import cn.com.inossem.activity.R;
import cn.com.inossem.config.WSConfig;
import cn.com.inossem.model.FriendInfoBean;
import cn.com.inossem.model.PhoneBook;
import cn.com.inossem.utils.AsyncImageLoader;
import cn.com.inossem.utils.Utils;
import cn.com.inossem.utils.AsyncImageLoader.ImageCallback;

public class YaoQingUserAdapter extends BaseAdapter {
	private List<PhoneBook> taskList;
	private LayoutInflater mLayoutInflater;
	private ViewHolder viewHolder;
	// private PhoneBook task;
	private String[] stringArr;
	private ArrayList<String> webNameArr;
	FriendInfoBean user_click = null;

	private List<PhoneBook> Xuanzhongmessage;
	private Context mContext;

	// public static ArrayList<String> mContactsName = new ArrayList<String>();
	private class ViewHolder {
		ImageView iv_type;
		TextView tv_name;
		TextView tv_detail;
		TextView tv_btn;
		public TextView firstCharHintTextView;
		public ImageView choose;
	}

	FriendList friend_list = null;

	public YaoQingUserAdapter(Context context, List<PhoneBook> taskList,
			ArrayList<String> webNameArr, List<PhoneBook> Xuanzhongmessage) {
		this.mLayoutInflater = LayoutInflater.from(context);
		this.taskList = taskList;
		this.friend_list = friend_list;
		this.Xuanzhongmessage = Xuanzhongmessage;
		this.webNameArr = webNameArr;
		this.mContext = context;
	}

	public void setInfoData(List<PhoneBook> taskList,
			ArrayList<String> webNameArr) {
		this.taskList = taskList;
		this.webNameArr = webNameArr;
	}

	public void updateTaskAdapter(List<PhoneBook> taskList) {
		this.taskList = taskList;
		this.notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return taskList == null ? 0 : taskList.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			viewHolder = new ViewHolder();
			LayoutInflater inflator = (LayoutInflater) parent.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = (LinearLayout) inflator.inflate(
					R.layout.yaoqinglist_user, null);
			// convertView = mLayoutInflater.inflate(R.layout.list_user, null);
			viewHolder.iv_type = (ImageView) convertView
					.findViewById(R.id.imageView1);
			viewHolder.tv_name = (TextView) convertView
					.findViewById(R.id.textView1);
			// viewHolder.tv_detail = (TextView)
			// convertView.findViewById(R.id.textView2);
			// viewHolder.tv_btn = (TextView)
			// convertView.findViewById(R.id.textView3);
			viewHolder.choose = (ImageView) convertView
					.findViewById(R.id.choose1);
			viewHolder.firstCharHintTextView = (TextView) convertView
					.findViewById(R.id.text_first_char_hint);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		final PhoneBook task = taskList.get(position);
		/*final ImageView imageView = new ImageView(mContext);
		imageView.setPadding(5, 0, 5, 5);
		imageView.setLayoutParams(new LayoutParams(Utils.dip2px(mContext, 80), Utils.dip2px(mContext, 80)));
		imageView.setTag(WSConfig.IMAGE_HEADER_URL + task.getImage());
		viewHolder.iv_type.setBackgroundDrawable(imageView.getDrawable());*/
		String image = task.getImage();
		if ((null != image) && (!image.equals(""))) {
			AsyncImageLoader asyncImageLoader = new AsyncImageLoader(mContext);
			Drawable drawable = asyncImageLoader.loadImageFromUrl(WSConfig.IMAGE_HEADER_URL + task.getImage());
			if (drawable != null) {
				viewHolder.iv_type.setBackgroundDrawable(new BitmapDrawable(Utils
						.toRoundCorner(Utils.drawableToBitmap(drawable), 300)));
			}
		} else {
			viewHolder.iv_type.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.touxiang));
		}
		/*try {
			Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(WSConfig.IMAGE_HEADER_URL + task.getImage()).getContent());
			viewHolder.iv_type.setBackgroundDrawable( new BitmapDrawable(bitmap));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		// if (!task.getImageData().equals("")) {
		// viewHolder.iv_type.setBackgroundDrawable(new BitmapDrawable(Utils
		// .toRoundCorner(stringtoBitmap(task.getImageData()), 50)));
		// }
		// viewHolder.iv_type.setBackgroundResource(task.icon_id);
		viewHolder.tv_name.setText(task.getFriendTruename());
		// viewHolder.tv_detail.setText(task.getPhone());
		// viewHolder.tv_btn.setText(task.getAdd());

		int idx = position - 1;
		// 判断前后Item是否匹配，如果不匹配则设置并显示，匹配则取消
		char previewChar = idx >= 0 ? webNameArr.get(idx).charAt(0) : ' ';
		char currentChar = webNameArr.get(position).charAt(0);
		// 将小写字符转换为大写字符
		char newPreviewChar = Character.toUpperCase(previewChar);
		char newCurrentChar = Character.toUpperCase(currentChar);
		if (newCurrentChar != newPreviewChar) {
			viewHolder.firstCharHintTextView.setVisibility(View.VISIBLE);
			viewHolder.firstCharHintTextView.setText(String
					.valueOf(newCurrentChar));
		} else {
			// 此段代码不可缺：实例化一个CurrentView后，会被多次赋值并且只有最后一次赋值的position是正确
			viewHolder.firstCharHintTextView.setVisibility(View.GONE);
		}

		final int index = position;

		if (task.getIsselected() == 1) {
			viewHolder.choose.setBackgroundResource(R.drawable.xuanze);
		} else {
			viewHolder.choose.setBackgroundResource(R.drawable.weixuanze);
		}

		// viewHolder.choose.setTag(viewHolder.choose);
		viewHolder.choose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (task.getIsselected() == 1) {
					task.setIsselected(0);
					// ((ImageView) v.getTag())
					// .setBackgroundResource(R.drawable.weixuanze);

					if (Xuanzhongmessage.contains(task)) {
						Xuanzhongmessage.remove(task);
					}
				} else {
					task.setIsselected(1);
					// ((ImageView) v.getTag())
					// .setBackgroundResource(R.drawable.xuanze);
					if (!Xuanzhongmessage.contains(task)) {
						Xuanzhongmessage.add(task);
					}
				}
				YaoQingUserAdapter.this.notifyDataSetChanged();
			}
		});
		// viewHolder.tv_btn.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// // taskList.remove(task);
		// // System.out.println("click ================== ");
		// // String str = friend_list.text_phone.getText().toString();
		// // System.out.println("str = "+str);
		// // if (str == null || str.equals(""))
		// // {
		// // showT();
		// // }
		// // else
		// // {
		// // UserPreferences upf = new UserPreferences(friend_list);
		// // upf.putStrData(UserPreferences.EDIT_TEXT_STR, str);
		// // friend_list.control_util.updatePhoneToService(str);
		// // user_click = taskList.get(index);
		// // String str_name = user_click.getUserName();
		// // String str_phone = user_click.getPhone();
		// // friend_list.control_util.requestAddFriend(str_name,
		// // str_phone);
		// //
		// // MobclickAgent.onEvent(friend_list, "click_add_friend_list");
		// // }
		// }
		// });
		return convertView;
	}

	public Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	// 12-04 17:04:06.707: I/System.out(13092):
	// {"username":"nugu","password":"123","equipType":"1","equipID":"0305271960c"}

	public void showT() {
		friend_list.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Toast.makeText(friend_list, "手机号码输入有误，请重新输入。",
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void removeUser() {
		taskList.remove(user_click);
		updateTaskAdapter(taskList);
	}
}